package com.xiaobao.campusLostFoundAfter.service.impl;

import com.xiaobao.campusLostFoundAfter.service.AvatarService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@Service
public class AvatarServiceImpl implements AvatarService {

    final String uploadDir = "D:/uploads/avatars";
    final String urlPrefix = "/uploads/avatars";
    final String contextPath = "http://172.20.10.2:8080/api";

    @Override
    public String saveAvatar(MultipartFile file, String userId, String fileExt) throws IOException {
        // 创建用户目录
        String userDir = uploadDir + File.separator + userId;
        File userDirectory = new File(userDir);
        if (!userDirectory.exists()) {
            boolean dirsCreated = userDirectory.mkdirs();
            if (!dirsCreated) {
                throw new IOException("无法创建用户目录: " + userDir);
            }
        }

        // 生成文件名
        String fileName = userId + "_" + System.currentTimeMillis() + "." + fileExt;
        String filePath = userDir + File.separator + fileName;

        // 保存文件
        Path targetLocation = Paths.get(filePath);
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

        // 构建完整URL（包含上下文路径）
        String fullUrl = urlPrefix + "/" + userId + "/" + fileName;

        // 如果urlPrefix不包含上下文路径，手动添加
        if (!fullUrl.contains(contextPath)) {
            fullUrl = fullUrl.replaceFirst("/", contextPath + "/");
        }
        return fullUrl;
    }
}